<?php
declare (strict_types = 1);

namespace app\controller;


use app\common\model\Content;
use app\common\model\Fav;
use app\common\model\Like;
use app\common\model\Unlike;
use app\service\ContentService;
/**
 * @OA\Info(
 *   title="Swagger文档自动生成，poweredBy qq571031767",
 *   version="1.0.0",
 *   @OA\Contact(
 *     email="571031767@qq.com",
 *     name="自动文档生成器，微信zg5710，微博@沙坪坝韩宇"
 *   )
 * )
 */

class ApiIndex extends ApiCommon
{
    private $field = 'id,title,prefimg,last_time,author,comment';
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * @OA\Response(
     *     response=200,
     *     description="successful operation",
     *     @OA\JsonContent(ref="/www/wwwroot/micuer.com/public"),
     * )
     */
    /**
     * @OA\Get(
     *   path="/index",
     *   summary="文章列表 - 首页",
     *   @OA\Response(
     *     response=200,
     *     description="文章首页列表"
     *   ),
     *   @OA\Response(
     *     response="default",
     *     description="an ""unexpected"" error"
     *   )
     * )
     */
    public function index()
    {
        $cid = input("param.cid");
        $page = input("param.page",1);
        $limit = input("param.limit",10);
        if($cid){
            $where["cate_id"] = 10;
        }
        $where["status"] = 1;
        if(!isset($where)){
            $where = 1;
        }

        $data = cache("data");
        if($data){
            return json(["code"=>200,"msg"=>"success","data"=>$data]);
        }

        //文章
        $list1 = \app\common\model\Content::where($where)
            ->where("model_id",1)
            ->order('id DESC')
            ->field($this->field)
            ->page($page)
            ->limit($limit)
            ->select();
        foreach ($list1 as $k => $v){
            $list1[$k]["prefimg"] = handlePic($v["prefimg"]);
            if(!$v["author"]){
                $list1[$k]["author"] = "米醋儿";
            }
        }

        //图集
        $list2 = \app\common\model\Content::where($where)
            ->where("model_id",4)
            ->order('id DESC')
            ->field($this->field)
            ->page($page)
            ->limit($limit)
            ->select();
        foreach ($list2 as $k => $v){
            $list2[$k]["prefimg"] = handlePic($v["prefimg"]);
            if(!$v["author"] || $v["author"] == 'null'){
                $list2[$k]["author"] = "米醋儿";
            }
        }
        //说说
        $list3 = \app\common\model\Content::where($where)
            ->where("model_id",5)
            ->order('id DESC')
            ->field($this->field)
            ->page($page)
            ->limit($limit)
            ->select();
        foreach ($list3 as $k => $v){
            $list3[$k]["prefimg"] = handlePic($v["prefimg"]);
            if(!$v["author"] || $v["author"] == 'null'){
                $list3[$k]["author"] = "米醋儿";
            }
        }
        //视频
        $list4 = \app\common\model\Content::where($where)
            ->where("model_id",2)
            ->order('id DESC')
            ->field($this->field)
            ->page($page)
            ->limit($limit)
            ->select();
        foreach ($list4 as $k => $v){
            $list4[$k]["prefimg"] = handlePic($v["prefimg"]);
            if(!$v["author"] || $v["author"] == 'null'){
                $list4[$k]["author"] = "米醋儿";
            }
        }
        $data = [
            $list1,
            $list2,
            $list3,
            $list4,
        ];
        cache("data",$data);
        if ($data){
            return json(["code"=>200,"msg"=>"success","data"=>$data]);
        }else{
            return json(["code"=>200,"msg"=>"success","data"=>$data]);
        }
    }

    public function more()
    {
        $cid = input("param.cid");
        $page = input("param.page",1);
        $limit = input("param.limit",10);
        $index = input("param.index",0); // 0文章 1图集 2说说 3视频

        if($cid){
            $where["cate_id"] = 10;
        }

        if($index == 0){
            $where["model_id"] = 1;
        }
        if($index == 1){
            $where["model_id"] = 4;
        }
        if($index == 2){
            $where["model_id"] = 5;
        }
        if($index == 3){
            $where["model_id"] = 2;
        }
        $where["status"] = 1;
        if(!isset($where)){
            $where = 1;
        }


        //文章
        $data = \app\common\model\Content::where($where)
            ->order('id DESC')
            ->field($this->field)
            ->page($page)
            ->limit($limit)
            ->select();
        //article_type 0大图 1单图缩略图在左侧 2单图缩略图在右侧 3多图【数组形式图片】
        foreach ($data as $k => $v){
            $data[$k]["prefimg"] = handlePic($v["prefimg"]);
            $data[$k]["image_url"] =[$data[$k]["prefimg"]];
            $data[$k]["article_type"] =2;
            if($v["comment_count"]>0){
                $data[$k]["comment_count"] = $v["comment_count"];
            }else{
                $data[$k]["comment_count"] = 0;
            }
            if(!$v["author"] || $v["author"] == 'null'){
                $data[$k]["author"] = "米醋儿";
            }
            $data[$k]["source"] = $data[$k]["author"];

            //更新文章的展现量
            update_hits($v["id"]);
        }
        if ($data){
            return json(["code"=>200,"msg"=>"success","data"=>$data]);
        }else{
            return json(["code"=>404,"msg"=>"success","data"=>$data]);
        }
    }

    //相关文档
    public function about_list()
    {
        //文章id
        $id = input("param.id");
        $content = Content::find($id);

        $cid = $content["cate_id"];
        $page = input("param.page",1);
        $limit = input("param.limit",10);
        $index = input("param.index",0); // 0文章 1图集 2说说 3视频

        if($cid){
            $where["cate_id"] = 10;
        }

        if($index == 0){
            $where["model_id"] = 1;
        }
        if($index == 1){
            $where["model_id"] = 4;
        }
        if($index == 2){
            $where["model_id"] = 5;
        }
        if($index == 3){
            $where["model_id"] = 2;
        }
        $where["status"] = 1;
        if(!isset($where)){
            $where = 1;
        }


        //文章
        $data = \app\common\model\Content::where($where)
            ->order('id DESC')
            ->field($this->field)
            ->page($page)
            ->limit($limit)
            ->select();
        //article_type 0大图 1单图缩略图在左侧 2单图缩略图在右侧 3多图【数组形式图片】
        foreach ($data as $k => $v){
            $data[$k]["prefimg"] = handlePic($v["prefimg"]);
            $data[$k]["image_url"] =[$data[$k]["prefimg"]];
            $data[$k]["article_type"] =2;
            if($v["comment_count"]>0){
                $data[$k]["comment_count"] = $v["comment_count"];
            }else{
                $data[$k]["comment_count"] = 0;
            }
            if(!$v["author"] || $v["author"] == 'null'){
                $data[$k]["author"] = "米醋儿";
            }
            $data[$k]["source"] = $data[$k]["author"];
            //更新文章的展现量
            update_hits($v["id"]);
        }
        if ($data){
            return json(["code"=>200,"msg"=>"success","data"=>$data]);
        }else{
            return json(["code"=>404,"msg"=>"success","data"=>$data]);
        }
    }

    //id
    public function detail()
    {
        $id  = input("param.id",1044);
        $token  = input("param.token");
        if($token){
            $user = jwt_decode($token);
            $uid = $user->uid;
        }else{
            $uid = '';
        }
        $content = Content::find($id);
        $is_md = $content["is_md"];//1markdown文本

        //更新文章的展现量 和 点击量
        update_hits($id,2);

        if($content["model_id"] == 1){
            //图文
            $article = \app\common\model\Article::where("contentid",$id)
                ->order("id DESC")
                ->find();
            if($is_md){
                $Parsedown = new \Parsedown();
                $article["info"] =  $Parsedown->text($article["info"]);
            }
            $article["info"] = str_replace('src="/public/','src="'.request()->domain().'/public/',$article["info"]);
            $res = $article;
        }

        //用户是否收藏了文章等
        if($token){
            $map["uid"] = $uid;
            $map["cid"] = $id;
            $fav = Fav::where($map)->find();
            if($fav){
                $res["fav"] = 1;
            }else{
                $res["fav"] = 0;
            }
            $where["aid"] = $id;
            $where["uid"] = $uid;
            $like_status = Like::where($where)->find();
            if($like_status){
                $res["like_status"] = 1;
            }else{
                $res["like_status"] = 0;
            }
            $unlike_status = Unlike::where($where)->find();
            if($unlike_status){
                $res["unlike_status"] = 1;
            }else{
                $res["unlike_status"] = 0;
            }
        }
        $res["hits"] = $content["hits"];
        $res["like"] = $content["like"];
        $res["unlike"] = $content["unlike"];

        //替换文章中的图片为配置的cdn前缀
        if(isset($article["article"]["info"])){
            $article["article"]["info"] = str_replace(\request()->domain(),config('web.cdn'),$article["article"]["info"]);
        }
        if(isset($res["info"])){
            $res["info"] = str_replace(\request()->domain(),config('web.cdn'),$res["info"]);
        }
        if(isset($content["info"])){
            $content["info"] = str_replace(\request()->domain(),config('web.cdn'),$content["info"]);
        }

        if ($content){
            return json(["code"=>200,"msg"=>"success","data"=>$res,"content"=>$content]);
        }else{
            return json(["code"=>404,"msg"=>"success","data"=>$res]);
        }
    }

    //发布动态 - 文章  小程序
    public function dongtai()
    {
        $d = input("param.");

        if(!isset($d["model_id"])){
            $d["model_id"] = 5;//发布动态
        }

        if($d["type"] == 'dongtai'){
            $d["model_id"] = 5;//发布动态
        }
        if($d["type"] == 'article'){
            $d["model_id"] = 1;//发布文章
        }
        if($d["type"] == 'tuji'){
            $d["model_id"] = 4;//发布
        }


        if($d["model_id"] == 4){
            if(!$d["uploadImgList"]){
                return json(["code"=>404,"msg"=>"请先上传图片"]);
            }
            //图集的图片处理
            $str = '';
            foreach ( $d["uploadImgList"] as $k=> $v){
                $str .= "<img src='".request()->domain().$v."'>";
            }
            $d["content"] = $str;
        }

        $user = $this->user;


        if(!$user){
            return json(["code"=>404,"msg"=>"请先登录"]);
        }

        $mod = new \app\common\model\Content();
        if(!isset($d["status"])){
            $d["status"] = 1;
        }
        //超级管理员选择了发布文章的用户
        if (isset($d["post_uid"]) && $d["post_uid"] != ''){
            $user = User::find($d["post_uid"]);
        }
        $d["uid"] = $user["id"];
        $d["author"] = $user["nickname"];
        $d["userinfo"] = json_encode($user);

        if(strlen($d["content"]) < 5){
            return  json(["code"=>4000,"msg"=>"文章内容过短"]);
        }



        //修改
        if(isset($d["id"])){
            $mod = Content::find($d["id"]);
        }

        if(!isset($d["cate_id"])){
            $d["cate_id"] = 0;
        }


        foreach ($d as $k => $v){
            if($v == null || !$v || $v=='null'){
                unset($d[$k]);
            }
        }


        if($d["model_id"] == 5 || $d["model_id"] ==1){
            $str = $d["content"];
            //获取第一行为标题
            $title = explode(PHP_EOL,$str);
            if(!$title[0]){
                return  json(["code"=>4000,"msg"=>"请用换行隔开动态的标题"]);
            }
            $d["title"] = $title[0];
        }

        $temp = $d["content"];
        $str = str_replace("*","",$str);
        $str = str_replace("`","",$str);
        $str = str_replace("\n","",$str);
        $str = str_replace("~","",$str);
        $str = str_replace(">","",$str);
        $str = str_replace("#","",$str);
        $str = str_replace("-","",$str);
        $str = str_replace("|","",$str);
        $str = str_replace("]","",$str);
        $str = str_replace("[","",$str);
        if(!isset($d["intro"])){
            $d["intro"] = mb_substr($str,0,500);
        }

        $d["info"] = $str;

        //有图
        if(isset($d['imgs']) && count($d["imgs"]) > 0){
            foreach ($d["imgs"] as $k=> $v){
                $d['imgs'][$k] = str_replace('"','',$v);
            }
            $d["prefimg"] = $d["imgs"][0]; //主图 为多图的第一个
            $d["imgs"] = json_encode($d["imgs"]);
        }
        $d["from"] = "微信小程序";

        if(isset($d["table-align"])){
            unset($d["table-align"]);
        }


        $res = $mod->save($d);

        //如果动态
        if($d["model_id"] == 5){
            $d["info"] = $temp;
            $d["contentid"] = $mod->id;
            if(isset($d["id"])){
                \app\common\model\News::where("contentid",$d["contentid"])
                    ->save($d);
            }else{
                \app\common\model\News::create($d);
            }

        }

        //如果文章 - 按时不支持文章内容添加图片
        if($d["model_id"] == 1){
            $d["info"] = $temp;
            $d["contentid"] = $mod->id;
            $d["info"] = $this->handleInfo($d["info"]);
            if(isset($d["id"])){
                \app\common\model\Article::where("contentid",$d["contentid"])
                    ->save($d);
            }else{
                \app\common\model\Article::create($d);
            }

        }

        //如果 图集 - 存到content表和 article表中
        if($d["model_id"] == 4){
            $d["info"] = $temp;
            $d["contentid"] = $mod->id;
            $d["info"] = $d["content"];
            $d["is_md"] = 0;

            if(isset($d["id"])){
                \app\common\model\Article::where("contentid",$d["contentid"])
                    ->save($d);
            }else{
                \app\common\model\Article::create($d);
            }

        }

        if($res){
            return  json(["code"=>200,"msg"=>"成功"]);
        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }
    }
    //发布图集- 文章  小程序
    public function tuji()
    {
        $d = input("param.");
        $d["model_id"] = 4;
        if(!$d["uploadImgList"]){
            return json(["code"=>404,"msg"=>"请先上传图片"]);
        }
        //图集的图片处理
        $str = '';
        foreach ( $d["uploadImgList"] as $k=> $v){
            $str .= "<img src='".request()->domain().$v."'>";
        }
        $d["content"] = $str;

        $user = $this->user;
        if(!$user){
            return json(["code"=>404,"msg"=>"请先登录"]);
        }
        $mod = new \app\common\model\Content();
        if(!isset($d["status"])){
            $d["status"] = 1;
        }

        if(strlen($d["content"]) < 5){
            return  json(["code"=>4000,"msg"=>"文章内容过短"]);
        }

        //修改
        if(isset($d["id"])){
            $mod = Content::find($d["id"]);
        }

        if(!isset($d["cate_id"])){
            $d["cate_id"] = 0;
        }


        foreach ($d as $k => $v){
            if($v == null || !$v || $v=='null'){
                unset($d[$k]);
            }
        }

        $d["info"] = $d["title"];
        $d["uid"] = $user["id"];
        $d["author"] = $user["nickname"];
        $d["userinfo"] = json_encode($user);
        
        //有图
        $d["imgs"] = $d["uploadImgList"];
        if(isset($d['imgs']) && count($d["imgs"]) > 0){
            foreach ($d["imgs"] as $k=> $v){
                $d['imgs'][$k] = str_replace('"','',$v);
            }
            $d["prefimg"] = $d["imgs"][0]; //主图 为多图的第一个
            $d["imgs"] = json_encode($d["imgs"]);
        }
        $d["from"] = "微信小程序";

        $res = $mod->save($d);

        $d["info"] = $d["content"];
        $d["contentid"] = $mod->id;
        $d["info"] = $this->handleInfo($d["info"]);
        $d["img"] = $d["prefimg"];
        if(isset($d["id"])){
            \app\common\model\Images::where("contentid",$d["contentid"])
                ->save($d);
        }else{
            \app\common\model\Images::create($d);
        }
        if($res){
            return  json(["code"=>200,"msg"=>"成功"]);
        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }
    }

    //我发布的内容列表
    public function my_contents()
    {
        //https://ext.dcloud.net.cn/plugin?id=209 前端文档
        $user = $this->user;

        $page = input("param.page",1);
        $limit = input("param.limit",10);
        $index = input("param.index",0); // 0文章 1图集 2说说 3视频



        //if($index == 0){
        //    $where["model_id"] = 1;
        //}
        //if($index == 1){
        //    $where["model_id"] = 4;
        //}
        //if($index == 2){
        //    $where["model_id"] = 5;
        //}
        //if($index == 3){
        //    $where["model_id"] = 2;
        //}
       
        if($user["id"] != 1137){//超管
            $where["uid"] = $user["id"];
        }

        if(!isset($where)){
            $where = 1;
        }

        //文章
        $data = \app\common\model\Content::where($where)
            ->order('id DESC')
            ->field($this->field)
            ->page($page)
            ->limit($limit)
            ->select();
        //article_type 0大图 1单图缩略图在左侧 2单图缩略图在右侧 3多图【数组形式图片】
        foreach ($data as $k => $v){
            $data[$k]["image"] = handlePic($v["prefimg"]);

            $data[$k]["image_url"] =[$data[$k]["prefimg"]];
            $data[$k]["article_type"] =2;
            if($v["comment_count"]>0){
                $data[$k]["comment_count"] = $v["comment_count"];
            }else{
                $data[$k]["comment_count"] = 0;
            }
            if(!$v["author"] || $v["author"] == 'null'){
                $data[$k]["author"] = "米醋儿";
            }
            $data[$k]["source"] = $data[$k]["author"];
            $data[$k]["slide_x"] = 0;
            if($v["info"]){
                $data[$k]["detail"] = strip_tags($v['info']);
            }else{
                $data[$k]["detail"] = '内有填写文章简介';
            }

            $data[$k]["rightDetail"] = date("Y-m-d", strtotime($v["last_time"]));


            //更新文章的展现量
            update_hits($v["id"]);
        }
        if ($data){
            return json(["code"=>200,"msg"=>"success","data"=>$data]);
        }else{
            return json(["code"=>404,"msg"=>"success","data"=>$data]);
        }

    }

    //将文章处成富文本
    public function handleInfo($str)
    {
        $arr = explode(PHP_EOL,$str);
        $str = '';
        foreach ($arr as $v){
            if($v){
                $str .= '<p>'.$v.'</p>';
            }
        }
        return $str;
    }

    //今日热门
    public  function hot_today()
    {
        $data = ContentService::hot_day();
        $page = input("param.page",1,"trim");
        if($page != 1){
            return json(["code"=>200,"msg"=>"success","data"=>""]);
        }
        if ($data){
            return json(["code"=>200,"msg"=>"success","data"=>$data]);
        }else{
            return json(["code"=>404,"msg"=>"success","data"=>$data]);
        }
    }

    //保存上传的小视频
    public function minvideo()
    {
        $user = $this->user;
        $d = \request()->post();
        $d["intro"] = $d["info"];
        $d["desc"] = $d["info"];
        $d["last_time"] = time();
        $d["from"] = "微信小程序";
        $d["uid"] = $user["id"];
        $d["author"] = $user["nickname"];
        $contentid = $d["id"];
        unset($d["add_time"]);
        unset($d["delete_time"]);
        unset($d["id"]);

        $res = Content::update($d,["id"=>$contentid]);
        $res1 = \app\common\model\Video::update($d,["contentid"=>$contentid]);

        if($res && $res1){
            return  json(["code"=>200,"msg"=>"成功"]);
        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }

    }

    public function change_status($id)
    {
        $status = request()->param("status");
        $res = Content::update(["status"=>$status],['id' => $id]);
        if($res){
            return  json(["code"=>200,"msg"=>"成功"]);
        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }
    }
}
